var threeSum = function(nums) {
  const len = nums.length;
  let ans = [];

  nums.sort((a, b) => a - b);

  for (let i = 0; i < len; i++) {
    let a = nums[i], left = i + 1, right = len - 1;
    if (i > 0 && a === nums[i - 1]) continue;

    while (left < right) {
      let b = nums[left], c = nums[right];
      if (a + b + c === 0) {
        ans.push([a, b, c]);
        while (left < right && b === nums[left+1]) {
          left++;
        }
        while (left < right && c === nums[right-1]) {
          right--;
        }
        left++, right--;
      } else if (a + b + c > 0) {
        right--;
      } else {
        left++;
      }
    }
  }

  return ans;
}

const nums = [1,2,-2,-1]
console.log(threeSum(nums))